import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { bindActionCreators } from 'redux';
import { actions as orgManageActions } from '@containers/asset-org-manage/reducer';
import { connect } from 'react-redux';
import { Button, Form, Input } from 'antd';
import { EMAIL_RE } from '@util/constants';
import './index.less';

const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  }
};

const OrgAccountTab = props => {
  const { form, accountData, updateZoomeyeOrgAccount, closeModal } = props;
  const { validateFields, setFieldsValue, getFieldDecorator } = form;
  const [disabled, setDisabled] = useState(false);
  const handleSubmit = () => {
    validateFields((err, values) => {
      if (err) {
        return;
      }
      updateZoomeyeOrgAccount(values);
    });
  };

  const handleResetKey = () => {
    setFieldsValue({ apiKey: '' });
    setDisabled(false);
  };

  useEffect(() => {
    if (accountData.apiKey) {
      const { email } = accountData;
      setFieldsValue({ email, apiKey: '********' });
      setDisabled(true);
    }
  }, [accountData, setFieldsValue]);

  return (
    <>
      <Form layout="horizontal" {...formItemLayout} labelAlign="left" className="org-account-form">
        <Form.Item label="邮箱">
          {getFieldDecorator('email', {
            rules: [
              { required: true, message: '请输入zoomeye.org的注册邮箱' },
              {
                pattern: EMAIL_RE,
                message: '您输入的格式有误'
              }
            ]
          })(<Input placeholder="请输入zoomeye.org的注册邮箱" />)}
        </Form.Item>
        <Form.Item label="API-KEY">
          {form.getFieldDecorator('apiKey', {
            rules: [
              { required: true, message: '请输入zoomeye.org的API-KEY' },
              { len: 36, message: '您输入的格式有误' }
            ]
          })(<Input placeholder="请输入zoomeye.org的API-KEY" disabled={disabled} />)}
          <Button type="link" onClick={handleResetKey}>
            重新输入
          </Button>
        </Form.Item>
      </Form>
      <div className="account-btn-group">
        <Button onClick={closeModal}>取&nbsp;&nbsp;&nbsp;消</Button>
        <Button type="primary" onClick={handleSubmit}>
          下一步
        </Button>
      </div>
    </>
  );
};

OrgAccountTab.propTypes = {
  closeModal: PropTypes.func,
  onSuccess: PropTypes.func,
  updateZoomeyeOrgAccount: PropTypes.func,
  handleTabChange: PropTypes.func,
  form: PropTypes.object,
  accountData: PropTypes.object
};

const mapStateToProps = state => {
  return {
    accountData: _.get(state, 'orgManage.accountData', false)
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(orgManageActions, dispatch)
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create()(OrgAccountTab));
